package com.xh.service.impl;

import com.xh.pojo.IMail;
import com.xh.service.IMailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/*
 * @author：Zero度
 * @2020/12/26 16:13
 * 文件说明：邮件发送服务类
 * */
@Service
public class IMailServiceImpl implements IMailService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * Spring Boot 提供了一个发送邮件的简单抽象
     */
    @Autowired
    private JavaMailSender mailSender;


    /**
     * 简单文本邮件
     * @param iMail
     */
    @Override
    public void sendSimpMail(IMail iMail) {
        // 创建SimpleMailMessage对象
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件发送人
        message.setFrom(iMail.getFrom());
        //邮件接收人
        message.setTo(iMail.getTo());
        //邮件主题
        String subject = iMail.getSubject() + "：您好";
        message.setSubject(subject);
        //邮件内容
        String content =
                "欢迎您访问xhblog.cn，期待您下次访问！！！" + "\n您的留言内容：" + iMail.getUpContent() + "\n博主回复：" +iMail.getContent();

        logger.info("邮件发送内容：" + content);
        message.setText(content);
        //发送邮件
        mailSender.send(message);
        //日志信息
        logger.info("邮件已发送");
    }

    @Override
    public String sendSimpHtml(IMail iMail) {
        // 创建MimeMessage
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);

            //邮件发送人
            messageHelper.setFrom(iMail.getFrom());
            //邮件接收人
            messageHelper.setTo(iMail.getTo());
            //邮件主题
            String subject = iMail.getSubject() + "：您好";
            message.setSubject(subject);
            //邮件内容
            String content =
                    "<h3 style=\"text-align: centent;\">欢迎您访问xhblog.cn</h3>" + "\n<p style=\"font-size:13px;" +
                            "color:#d3d3d3;" +
                            "\">您的留言内容：" + iMail.getUpContent() +
                            "<p>\n<h5>博主回复：" +iMail.getContent() + "</h5>";
            messageHelper.setText(content, true);

            //发送邮件
            mailSender.send(message);
            //日志信息
            logger.info("邮件已发送");

            return "发送成功";
        } catch (MessagingException e) {
            e.printStackTrace();
            return "发送失败，请查错";
        }

    }
}
